package com.hancher.gamelife2.birthday;

import static com.hancher.gamelife2.backup.BaiduNetManager.BAIDU_API_UPLOAD_MESSAGE_PATH;

import android.os.Bundle;

import androidx.navigation.Navigation;
import androidx.sqlite.db.SimpleSQLiteQuery;

import com.bumptech.glide.Glide;
import com.hancher.common.androidutil.AsyncUtils;
import com.hancher.common.androidutil.GlideEngine;
import com.hancher.common.androidutil.LogUtil;
import com.hancher.common.androidutil.MmkvUtil;
import com.hancher.common.androidutil.PathUtil;
import com.hancher.common.androidutil.ToastUtil;
import com.hancher.common.base.BaseFragment;
import com.hancher.common.javautil.DateUtil;
import com.hancher.common.javautil.EmptyUtil;
import com.hancher.common.javautil.FileUtil;
import com.hancher.common.javautil.UuidUtil;
import com.hancher.common.lunarsolarpicker.view.DialogGLC;
import com.hancher.gamelife2.R;
import com.hancher.gamelife2.backup.BaiduNetApi;
import com.hancher.gamelife2.backup.BaiduNetManager;
import com.hancher.gamelife2.databinding.FragmentBirthdayEditBinding;
import com.hancher.gamelife2.main.MainDatabase_Impl;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.nlf.calendar.Lunar;
import com.nlf.calendar.Solar;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import io.reactivex.rxjava3.functions.Consumer;

/**
 * 作者 : Hancher ytu_shaoweijie@163.com <br/>
 * 时间 : 2023/3/12 0012 22:49 <br/>
 * 描述 :
 */
public class BirthdayEditFragment extends BaseFragment<FragmentBirthdayEditBinding> {

    String recordUuid;
    BirthdayPO birthday;
    private static String faceCachePath = PathUtil.OUT_APP_CACHE + File.separator + "setting" + File.separator + "BirthdayFace.jpg";
    private LoadingPopupView waitDialog;
    private String recordUrl;

    @Override
    protected void initView(Bundle savedInstanceState) {
        if (getArguments() != null) {
            recordUuid = getArguments().getString("data");
            recordUrl = getArguments().getString("url");
        }
    }

    @Override
    protected void initData() {
        if (EmptyUtil.isEmpty(recordUuid)) {
            birthday = new BirthdayPO();
            updateData();
        } else {
            if (EmptyUtil.isNotEmpty(recordUrl)) {
                Glide.with(binding.imgHeader).load(recordUrl).into(binding.imgHeader);
            }
            AsyncUtils.run(emitter -> {
                String sql = " SELECT * FROM birthday  WHERE deleteflag!=1 AND uuid='" + recordUuid + "' ";
                List<BirthdayPO> birthdayPOS = MainDatabase_Impl.getInstance().birthdayDao().getList(new SimpleSQLiteQuery(sql));
                if (EmptyUtil.isNotEmpty(birthdayPOS)) {
                    emitter.onNext(birthdayPOS.get(0));
                }
            }, (Consumer<BirthdayPO>) data -> {
                birthday = data;
                updateData();
            });
        }
    }

    @Override
    protected void initListener() {
        binding.female.setOnClickListener(v -> changeFemale(true));
        binding.man.setOnClickListener(v -> changeFemale(false));
        binding.itemSolar.setOnClickListener(v -> showInDialog());
        binding.itemLunar.setOnClickListener(v -> showInDialog());
        binding.imgHeader.setOnClickListener(v -> {
            File file2 = new File(faceCachePath);
            if (file2.exists()) {
                file2.delete();
            }
            checkSelectImagePermission();
        });
        //保存
        binding.hrPrimaryButton.setOnClickListener(v -> {
            birthday.setName(binding.editBirthdayName.getText().toString());
            birthday.setContent(binding.editMessage.getText().toString());
            birthday.setIsSolar(binding.swSolar.isHrCheck());
            birthday.setIsLunar(binding.swLunar.isHrCheck());
            if (birthday.getFemale() == null) {
                ToastUtil.showErr("未选择性别");
                return;
            }
            if (birthday.getSolarY() == null) {
                ToastUtil.showErr("未选择生日");
                return;
            }
            if (birthday.getName() == null) {
                ToastUtil.showErr("未选择姓名");
                return;
            }
            if (binding.swMe.isHrCheck()) {
                MmkvUtil.put("BIRTHDAY_ME_UUID", birthday.getUuid());
            }
            if (EmptyUtil.isNotEmpty(birthday.getImgCachePath())) {
                //  保存
                waitDialog = (LoadingPopupView) new XPopup.Builder(getContext())
                        .dismissOnBackPressed(false)
                        .dismissOnTouchOutside(false)
                        .asLoading("正在加载中")
                        .show();
                AsyncUtils.run(emitter -> {
                    BaiduNetManager.getInstance().uploadFile(birthday.getImgCachePath(), BaiduNetApi.BDPAN_BACKUP_PATH +
                            DateUtil.getYearMonthstr2() + File.separator + UuidUtil.getUuidNoLine() + ".jpg");
                }, data -> {

                });
                return;
            }
//            if (!birthday.getSolar() && !birthday.getLunar()){
//                ToastUtil.show("阴历、阳历必须启用一个");
//                return;
//            }
            saveImage();
        });
        LiveEventBus.get(BAIDU_API_UPLOAD_MESSAGE_PATH, BaiduNetApi.UploadFinishVO.class)
                .observe(this, uploadFinishVO -> {
                    birthday.setFsids(uploadFinishVO.getFs_id());
                    birthday.setImage(uploadFinishVO.getPath());
                    saveImage();
                });
    }

    private void saveImage() {
        AsyncUtils.run(emitter -> {
            if (EmptyUtil.isNotEmpty(recordUuid)) {
                birthday.setUpdateTime(System.currentTimeMillis());
                MainDatabase_Impl.getInstance().birthdayDao().updateItem(birthday);
            } else {
                MainDatabase_Impl.getInstance().birthdayDao().insertItem(birthday);
            }
            emitter.onNext("");
            emitter.onComplete();
        }, (Consumer<String>) s -> {
            if (waitDialog != null && waitDialog.isShow()) {
                waitDialog.dismiss();
            }
            if (EmptyUtil.isEmpty(recordUuid)) {
                Navigation.findNavController(binding.container).popBackStack();
            }
        });
    }

    //region 选择图片
    private void checkSelectImagePermission() {
        // 权限检查
        XXPermissions.with(this)
                .permission(Permission.WRITE_EXTERNAL_STORAGE,
                        Permission.READ_MEDIA_IMAGES,
                        Permission.READ_MEDIA_VIDEO,
                        Permission.READ_MEDIA_AUDIO,
                        Permission.CAMERA)
                .request((permissions, allGranted) -> {
                    if (allGranted) {
                        selectImage();
                    } else {
                        ToastUtil.show("权限未全部同意！");
                    }
                });
    }

    private void selectImage() {
        // 图片选择
        PictureSelector.create(this)
                .openGallery(SelectMimeType.ofImage())
                .setImageEngine(GlideEngine.createGlideEngine())
                .setMaxSelectNum(1)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        for (LocalMedia item : result) {
                            LogUtil.o(item);
                        }
                        if (EmptyUtil.isEmpty(result)) {
                            ToastUtil.showErr("选择文件失败!");
                            return;
                        }
                        String cameraPicPath = result.get(0).getRealPath();
                        File cameraFile = new File(cameraPicPath);
                        File faceCacheFile = new File(faceCachePath);
                        LogUtil.d("2. 获得拍照图片 %s, %b", cameraPicPath, cameraFile.exists());
                        if (!cameraFile.exists()) {
                            ToastUtil.show("未获取到选择图片");
                        }
                        FileUtil.copyFile2File(cameraFile, faceCacheFile);
                        new XPopup.Builder(getContext())
                                .asCustom(new SelectFaceDialog(getContext(), faceCacheFile, uploadFinishVO -> {
                                    // TODO: 2024/1/15 保存到diary
                                    birthday.setImgCachePath(uploadFinishVO);
                                    Glide.with(binding.imgHeader).load(uploadFinishVO).into(binding.imgHeader);
                                }))
                                .show();
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }
    //endregion

    private void updateData() {
        binding.editBirthdayName.setText(birthday.getName());
        changeFemale(birthday.getFemale());
        updateBirthday();
        binding.editMessage.setText(birthday.getContent());
        binding.swSolar.setHrCheck(birthday.getIsSolar());
        binding.swLunar.setHrCheck(birthday.getIsLunar());
        String meUuid = MmkvUtil.getString("BIRTHDAY_ME_UUID", "");
        binding.swMe.setHrCheck(EmptyUtil.isNotEmpty(meUuid) && meUuid.equals(birthday.getUuid()));
    }

    /**
     * 修改性别
     * @param isFemale
     */
    private void changeFemale(boolean isFemale) {
        if (isFemale) {
            binding.female.setImageResource(R.drawable.famale_selected);
            binding.man.setImageResource(R.drawable.man_unselect);
        } else {
            binding.female.setImageResource(R.drawable.female_unselect);
            binding.man.setImageResource(R.drawable.man_selected);
        }
        birthday.setFemale(isFemale);
    }

    //region 农历选择
    private DialogGLC mDialog;

    /**
     * 显示农历选择器
     */
    private void showInDialog() {
        if (mDialog == null) {
            Calendar calendar = Calendar.getInstance();
            if (birthday == null || birthday.getSolarY() == null || birthday.getSolarY() < 1900) {
                calendar.set(1994, DateUtil.getMonth() - 1, DateUtil.getDay() > 28 ? 1 : DateUtil.getDay());
            } else {
                calendar.set(birthday.getSolarY(), birthday.getSolarM() - 1, birthday.getSolarD());
            }
            mDialog = new DialogGLC(getContext(), calendar);
        }
        mDialog.setListener((solarY, solarM, solarD, lunarY, lunarM, lunarD) -> {
            birthday.setSolarY(solarY);
            birthday.setSolarM(solarM);
            birthday.setSolarD(solarD);
            birthday.setLunarY(lunarY);
            birthday.setLunarM(lunarM);
            birthday.setLunarD(lunarD);
            updateBirthday();
            mDialog.dismiss();
        });

        mDialog.setCancelable(true);
        mDialog.setCanceledOnTouchOutside(true);
        mDialog.show();
        mDialog.initCalendar();
    }
    //endregion

    /**
     * 更新生日
     */
    private void updateBirthday() {
        Solar solar = new Solar(birthday.getSolarY(), birthday.getSolarM(), birthday.getSolarD());
        Lunar lunar = solar.getLunar();
        binding.txtLunarContent.setText(lunar.toString());
        binding.txtSolarContent.setText(solar.toString());
    }
}